﻿using Microsoft.Extensions.DependencyInjection;
using System.Linq;
using System.Reflection;

namespace Yuchen.NPA.Core
{
    public static class NPAExtension
    {
        public static IServiceCollection AddNPA<T, TEntity>(this IServiceCollection services)
        where T : class
        where TEntity : class
        {
            services.AddScoped<T>(provider =>
            {
                var proxy = DispatchProxy.Create<T, NPAProxy<T, TEntity>>();
                var proxyInterface = proxy as INpaProxy<TEntity>;
                var repositoryType = typeof(T);
                if (!EntityMetaData.EntityKeys.ContainsKey(repositoryType))
                {
                    var keyType = repositoryType.GetInterfaces()
                          .Where(x => x.IsGenericType).Where(x =>
                              typeof(INpaRepository<,>) == x.GetGenericTypeDefinition())
                          .FirstOrDefault()
                          .GetGenericArguments()[1];
                    EntityMetaData.EntityKeys.Add(repositoryType, keyType);
                }
                proxyInterface.CommandExecutor = provider.GetRequiredService<ICommandExecutor<TEntity>>();
                return proxy;
            });
            return services;
            //var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.DefinedTypes)
            //      .Where(x => typeof(INpaRepository<>).IsAssignableFrom(x)).ToList();
            //foreach (var typeInfo in types)
            //{
            //}
        }
    }
}
